package com.ciwong.epaper.modules.epaper.ui;

import android.app.Dialog;
import android.content.Intent;
import android.graphics.Color;
import android.net.TrafficStats;
import android.support.v4.view.ViewPager;
import android.text.Spannable;
import android.text.SpannableStringBuilder;
import android.text.TextUtils;
import android.text.style.ForegroundColorSpan;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.android.volley.TimeoutError;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.resource.bitmap.CenterCrop;
import com.ciwong.ciwongwrite.utils.CWUtils;
import com.ciwong.epaper.R;
import com.ciwong.epaper.application.EApplication;
import com.ciwong.epaper.modules.bookstore.bean.PublishWorkContent;
import com.ciwong.epaper.modules.epaper.adapter.ChooseWorkContentAdapter;
import com.ciwong.epaper.modules.epaper.bean.CatalogueInfo;
import com.ciwong.epaper.modules.epaper.bean.CatelogBean;
import com.ciwong.epaper.modules.epaper.bean.EpaperInfo;
import com.ciwong.epaper.modules.epaper.bean.Node;
import com.ciwong.epaper.modules.epaper.bean.PackageInfo;
import com.ciwong.epaper.modules.epaper.dao.EpaperDao;
import com.ciwong.epaper.modules.epaper.util.EpaperJumpManager;
import com.ciwong.epaper.modules.epaper.util.LayersView;
import com.ciwong.epaper.modules.epaper.util.ScrollViewExtend;
import com.ciwong.epaper.modules.epaper.util.ViewPageTitle;
import com.ciwong.epaper.modules.me.bean.FavoritesBook;
import com.ciwong.epaper.modules.me.bean.RefreshNewBookDesk;
import com.ciwong.epaper.util.BaseExtCallBack;
import com.ciwong.epaper.util.DialogUtil;
import com.ciwong.epaper.util.EConstants;
import com.ciwong.epaper.util.GlideRoundTransform;
import com.ciwong.epaper.util.HttpRequest;
import com.ciwong.epaper.util.IntentFlag;
import com.ciwong.epaper.util.IntentValue;
import com.ciwong.epaper.util.RequestCode;
import com.ciwong.epaper.util.SerializableManager;
import com.ciwong.eventbus.EventBus;
import com.ciwong.libs.utils.CWSys;
import com.ciwong.libs.utils.volley.BaseRequest;
import com.ciwong.mobilelib.i.BaseCallBack;
import com.ciwong.mobilelib.ui.BaseActivity;
import com.ciwong.mobilelib.utils.BaseIntentFlag;
import com.ciwong.mobilelib.utils.ThreadTask;
import com.ciwong.mobilelib.utils.ToastUtil;
import com.ciwong.mobilelib.widget.CWDialog;
import com.ciwong.mobilelib.widget.TitleBar;
import com.jude.rollviewpager.adapter.StaticPagerAdapter;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

/**
 * 书籍目录页面
 */
public class TeaCatalogActivity extends BaseActivity implements ScrollViewExtend.ScrollViewListener, View.OnClickListener, ViewPageTitle.ViewPageChanag {


    private LayoutInflater mInflater;
    private List<String> pageTitles;
    private ViewPager viewpager_catalog;


    private ScrollViewExtend mScrollView;

    private int mSubjectId = -1;

    //控件
    private TitleBar titleBar;
    private TextView bookTitle, mTvGrade, mTvWatches;
    private ImageView bookCovImage, mIvKaoShi, mIvFree;


    //----------------------业务相关
    private FavoritesBook mInfo;
    private String mBookId;
    private int from;// 来源

    //--------------返回数据
    private CatelogBean catelogBean;
    private List<Node> dataPack = new ArrayList<>();
    private int workTag = 1;
    //是否收藏（取消收藏）成功
    private Boolean isFavorites = false;
    private int JUMP_TO_CHOOSE_WORK_CONTENT = 10010;


    //获取通过Mobile连接收到的字节总数
    private long total_data = TrafficStats.getTotalRxBytes();

    /**
     * 扫一扫数据所属的服务列表
     */
    private List<EpaperInfo.Server> mEpaperServerList;

    private Boolean isShow = false;

    /**
     * 服务ID
     */
    private int mServiceId;

    //错误提示信息
    private Object mesData;
    private String tag;

    private ImageView tea_catalog_go_back;
    private TextView tea_catalog_title;
    private TextView service_name;
    private RelativeLayout favorites_lay;
    private ImageView favorive_book_img;
    private ImageView favorites_icon;
    private RelativeLayout favorites_lay2;
    private ImageView favorive_book_img2;
    private ImageView favorites_icon2;
    private ImageView favorites_tip2;
    private ImageView favorites_tip1;
    private LinearLayout work_content_lay;
    private ImageView work_folder;
    private RelativeLayout work_content_count_lay;
    private TextView work_content_count_text;
    private TextView refAnswerTime_text;
    private RelativeLayout go_to_publish_work;
    private ListView choose_work_content_list;
    private LinearLayout choose_work_content_lay;
    private ImageView close_choose_work_content;

    //预计作业耗时
    private int refAnswerTime;
    //作业内容适配器
    private ChooseWorkContentAdapter chooseWorkContentAdapter;

    private List<CatalogueInfo> mCatalogueInfos = new ArrayList<>();

    private ArrayList<String> bookchapters = new ArrayList<String>();

    private String userId;

    //作业内容
    private List<PublishWorkContent> publishWorkContentList = new ArrayList<>();


    @Override
    protected int setView() {
        return R.layout.activity_tea_catalog;
    }

    @Override
    protected void findViews() {

        try {
            titleBar = findViewById(R.id.activity_base_titlebar);
            mScrollView = findViewById(R.id.scro_mian);
            bookTitle = findViewById(R.id.book_title);
            bookCovImage = findViewById(R.id.book_cov);
            mTvGrade = findViewById(R.id.tv_grade);
            mIvKaoShi = findViewById(R.id.img_kaoshi);
            mIvFree = findViewById(R.id.img_free);
            //tea_catalog_go_back = findViewById(R.id.tea_catalog_go_back);
            viewpager_catalog = findViewById(R.id.viewpager_catalog);
            tea_catalog_title = findViewById(R.id.tea_catalog_title);
            service_name = findViewById(R.id.service_name);
            favorites_lay = findViewById(R.id.favorites_lay);
            favorites_tip2 = findViewById(R.id.favorites_tip2);
            favorites_tip1 = findViewById(R.id.favorites_tip1);
            favorive_book_img = findViewById(R.id.favorive_book_img);
            favorites_icon = findViewById(R.id.favorive_book_img);
            favorites_lay2 = findViewById(R.id.favorites_lay2);
            favorive_book_img2 = findViewById(R.id.favorive_book_img2);
            favorites_icon2 = findViewById(R.id.favorive_book_img2);
            work_content_lay = findViewById(R.id.work_content_lay);
            work_folder = findViewById(R.id.work_folder);
            work_content_count_lay = findViewById(R.id.work_content_count_lay);
            work_content_count_text = findViewById(R.id.work_content_count_text);
            refAnswerTime_text = findViewById(R.id.refAnswerTime_text);
            go_to_publish_work = findViewById(R.id.go_to_publish_work);
            favorive_book_img.setOnClickListener(this);
            favorive_book_img2.setOnClickListener(this);
        } catch (NullPointerException e) {
            e.getStackTrace();
        }


    }

    @Override
    protected void loadData() {
        //先加载本地数据
        loadNetData();
        getLocalPublishWork();
    }

    /**
     * 更新数据
     */
    private void upData() {

        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                hideCricleProgress();
                if (catelogBean.getPackages() != null) {
                    if (!TextUtils.isEmpty(catelogBean.getPackages().getGradeId())) {
                        String grade = EConstants.GRADE_DATA.get(Integer.parseInt(catelogBean.getPackages().getGradeId()));
                        if (!TextUtils.isEmpty(grade)) {
                            mTvGrade.setText("适用于:  " + grade);
                        } else {
                            mTvGrade.setText("适用于:  无 ");
                        }

                    }

                }

                mIvKaoShi.setVisibility(mInfo.getRequired() == 1 ? View.VISIBLE : View.INVISIBLE);
                mIvFree.setVisibility(mInfo.getIsFree() == 1 ? View.VISIBLE : View.INVISIBLE);


                if (catelogBean != null) {
                    dataPack.clear();
                    for (int i = 0; i < catelogBean.getPackages().getPackageinfo().size(); i++) {
                        dataPack.add(new Node(i + 1, 0, null, catelogBean.getPackages().getPackageinfo().get(i)));
                    }
                    //所属服务本地取
                    if (from == IntentValue.JumpToBookCatalogType.FROM_SCAN) {
                        //扫描二维码
                        if (mEpaperServerList != null) {
                            StringBuffer sbSer = new StringBuffer();
                            for (int i = 0; i < mEpaperServerList.size(); i++) {
                                if (i == (mEpaperServerList.size() - 1)) {
                                    sbSer.append(mEpaperServerList.get(i).getName());
                                } else {
                                    sbSer.append(mEpaperServerList.get(i).getName() + ",");
                                }
                            }
                            dataPack.add(new Node(-1, 0, null, new PackageInfo(0, 0, "所属服务", sbSer.toString())));
                        }
                    } else {
                        dataPack.add(new Node(-1, 0, null, new PackageInfo(0, 0, "所属服务", mInfo.getServiceName())));

                    }

                }
                initViewPage();
                try {

                    bookCovImage.setVisibility(View.VISIBLE);
                    try {
                        if (!isFinishing()) {
                            if (TeaCatalogActivity.this != null) {
                                String cover = "";
                                if (null != mInfo.getCover()) {
                                    cover = mInfo.getCover();
                                } else if (null != catelogBean && null != catelogBean.getPackages()) {
                                    cover = catelogBean.getPackages().getCover();
                                }
                                Glide.with(TeaCatalogActivity.this).load(cover).transform(new CenterCrop(TeaCatalogActivity.this), new GlideRoundTransform(TeaCatalogActivity.this, 6)).into(bookCovImage);
                            }
                        }
                    } catch (Exception e) {

                    }
                } catch (Exception e) {
                    e.getStackTrace();
                }

            }
        });


        //
    }

    private void loadNetData() {
        showLoadingView();
        EpaperDao.getInstance().getBookCatalogue(mBookId, userId, "", mServiceId + "", null, new BaseExtCallBack(TeaCatalogActivity.this, EApplication.getInstance().getUserInfoBase().getUserId() + "") {
            @Override
            public void success(final Object data) {
                hidenLoadingView();
                try {
                    //后台没数据临时用之前的接口
                    catelogBean = (CatelogBean) data;
                    if (catelogBean != null) {
                        mCatalogueInfos.clear();
                        mCatalogueInfos = catelogBean.getCatalogues();
                        mSubjectId = catelogBean.getPackages().getSubjectId();
                        if (null == mInfo.getProductName()) {
                            mInfo.setProductName(catelogBean.getPackages().getBook_name());
                            bookTitle.setText(catelogBean.getPackages().getBook_name());
                        }
                        if (0 == mInfo.getSubject()) {
                            mInfo.setSubject(mSubjectId);
                        }
                    }
                    upData();
                } catch (Exception e) {
                    e.getStackTrace();
                }

            }

            @Override
            public void failed(int errorCode, Object data) {
                hidenLoadingView();
                hideMiddleProgressBar();
                //网络获取失败了再走本地获取流程
                super.failed(errorCode, data);
                mesData = data;
                toError();
            }

            @Override
            public void failed(Object data) {
                hidenLoadingView();
                //                        getLocData();
                hideMiddleProgressBar();
                super.failed(data);
                mesData = data;
                toError();
            }
        });
    }

    private void toError() {
        if (catelogBean == null) {
            DialogUtil.showFailedToastByErrorType(TeaCatalogActivity.this, mesData);
        }
    }


    @Override
    protected void preCreate() {
        mInfo = (FavoritesBook) getIntent().getSerializableExtra(BaseIntentFlag.INTENT_FLAG_OBJ);
        from = getIntent().getIntExtra(BaseIntentFlag.INTENT_FLAG_ACTION, IntentValue.JumpToBookCatalogType.NORMAL);
        //服务器没有数据所以先用死的
        if (mInfo != null) {
            if (0 != mInfo.getPackageId()) {
                mBookId = String.valueOf(mInfo.getPackageId());
                //                            mBookId = "2760";
                mInfo.setPackageId(Integer.parseInt(mBookId));
            } else {
                mBookId = String.valueOf(mInfo.getProductId());
                //                            mBookId = "2760";
                mInfo.setPackageId(Integer.parseInt(mBookId));
            }

        }
        mServiceId = getIntent().getIntExtra(IntentFlag.INTENT_FLAG_SERVICE_ID, -1);
        mEpaperServerList = (List<EpaperInfo.Server>) getIntent().getSerializableExtra(IntentFlag.INTENT_FLAG_OBJ_LIST);
        tag = getIntent().getStringExtra(IntentFlag.INTENT_FLAG_TAG);
        if (TextUtils.isEmpty(tag)) {
            tag = RequestCode.TeaWorkContent.HOME_WORK;
        }
    }

    @Override
    protected void init() {
        //        TAG = "LayersView";
        setTitleText("书籍目录");
        try {
            isShow = CWSys.getSharedBoolean(EConstants.SHARE_KEY_FAVORITES_IS_SHOW_LSW_TIP, false);
        } catch (Exception e) {
        }

        mInflater = LayoutInflater.from(this);
        //        mScrollView.setScrollViewListener(this);
        bookTitle.setText(mInfo.getProductName());
        service_name.setText("所在服务：" + mInfo.getServiceName());
        BaseRequest.VerifyInfo verifyInfo = HttpRequest.getVerifyInfo();
        if (verifyInfo != null) {
            userId = EApplication.getInstance().getUserInfoBase().getUserId() + "";
        }
        if (mInfo.getIstop() == 1) {
            favorites_lay.setVisibility(View.VISIBLE);
            favorites_lay2.setVisibility(View.GONE);
            if (isShow) {
                favorites_tip1.setVisibility(View.GONE);
            } else {
                favorites_tip1.setVisibility(View.VISIBLE);
            }
        } else {
            favorites_lay.setVisibility(View.GONE);
            favorites_lay2.setVisibility(View.VISIBLE);
            if (isShow) {
                favorites_tip2.setVisibility(View.GONE);
            } else {
                favorites_tip2.setVisibility(View.VISIBLE);
            }
        }

    }


    private void initViewPage() {
        pageTitles = new ArrayList<String>();
        pageTitles.add("内容目录");
        viewpager_catalog.setAdapter(new TeaCatalogActivity.ViewPageTest(pageTitles));


    }

    @Override
    protected void initEvent() {
        work_folder.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (publishWorkContentList.size() == 0) {

                } else {
                    // choose_work_content_lay.setVisibility(View.VISIBLE);
                    showBottomDiaLog();
                    chooseWorkContentAdapter = new ChooseWorkContentAdapter(publishWorkContentList, TeaCatalogActivity.this);
                    choose_work_content_list.setAdapter(chooseWorkContentAdapter);
                }
            }
        });

        go_to_publish_work.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (null != publishWorkContentList && publishWorkContentList.size() > 0) {
                    setLocalData();
                    EpaperJumpManager.jumpToTeaPublishWork(R.id.go_back, TeaCatalogActivity.this, tag, mInfo.getProductName(), mInfo.getServiceId(), publishWorkContentList, mInfo.getSubject());
                } else {
                    ToastUtil.INSTANCE.toastCenterError(getString(R.string.choose_work_content));
                }
            }
        });

    }

    /**
     * 设置作业内容
     *
     * @param code
     * @param versionId
     * @param resourceUrl  资源url
     * @param resourceName 资源名
     */
    public void setWorkCountAndTimeConsuming(int code, String versionId, String resourceUrl, String resourceName) {
        if (1 == code) {
            if (publishWorkContentList.size() > 1) {
                work_content_lay.setVisibility(View.VISIBLE);
                int workCount = publishWorkContentList.size() - 1;
                work_content_count_text.setText(workCount + "");

            } else {
                work_content_lay.setVisibility(View.GONE);
                bottomDialog.dismiss();
            }

            for (int i = 0; i < publishWorkContentList.size(); i++) {
                if (null != resourceUrl && !"".equals(resourceUrl)) {
                    if (resourceUrl.equals(publishWorkContentList.get(i).getResourceUrl())) {
                        publishWorkContentList.remove(i);
                        break;
                    }
                } else {
                    if (resourceName.equals(publishWorkContentList.get(i).getResourceName())) {
                        publishWorkContentList.remove(i);
                        break;
                    }
                }
            }
            setWorkLong();

        } else {
            if (publishWorkContentList.size() > 0) {
                work_content_lay.setVisibility(View.VISIBLE);
                int workCount = publishWorkContentList.size();
                work_content_count_text.setText(workCount + "");

            } else {
                work_content_lay.setVisibility(View.GONE);
            }
        }

    }

    private Dialog bottomDialog;

    private void showBottomDiaLog() {
        bottomDialog = new Dialog(TeaCatalogActivity.this, R.style.BottomDialog);
        View contentView = LayoutInflater.from(TeaCatalogActivity.this).inflate(R.layout.activity_workcontent_bottom_dialog, null);
        choose_work_content_lay = contentView.findViewById(R.id.choose_work_content_lay);
        close_choose_work_content = contentView.findViewById(R.id.close_choose_work_content);
        choose_work_content_list = contentView.findViewById(R.id.choose_work_content_list);
        bottomDialog.setContentView(contentView);
        Window window = bottomDialog.getWindow();
        window.setGravity(Gravity.BOTTOM);
        ViewGroup.LayoutParams layoutParams = contentView.getLayoutParams();
        layoutParams.width = getResources().getDisplayMetrics().widthPixels;
        layoutParams.height = getResources().getDisplayMetrics().heightPixels / 3;
        contentView.setLayoutParams(layoutParams);
        close_choose_work_content.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                //choose_work_content_lay.setVisibility(View.GONE);
                bottomDialog.dismiss();
            }
        });
        bottomDialog.show();
    }


    @Override
    public void onScrollChanged(int x, int y, int oldx, int oldy) {
        //通过标题的y坐标来判断
        //        if (y >= (page_titles.getY() - topLin.getHeight())) {
        //            mViewPageTitleXiFu.setVisibility(View.VISIBLE);
        //            backIma.setImageResource(R.mipmap.back_book);
        //            topLin.setBackgroundColor(this.getResources().getColor(R.color.green));
        //            titleText.setVisibility(View.VISIBLE);
        //            page_titles.setVisibility(View.INVISIBLE);
        //            Log.e(TAG, "onScrollChanged: mViewPageTitleXiFu VISIBLE" );
        //        } else {
        //            topLin.setBackgroundColor(this.getResources().getColor(R.color.transparent));
        //            backIma.setImageResource(R.mipmap.v_back);
        //            page_titles.setVisibility(View.VISIBLE);
        //            mViewPageTitleXiFu.setVisibility(View.INVISIBLE);
        //            titleText.setVisibility(View.INVISIBLE);
        //            Log.e(TAG, "onScrollChanged: mViewPageTitleXiFu INVISIBLE" );
        //        }
    }


    /**
     * item监听事件
     *
     * @param catalogueInfo
     */
    public void doClickListener(final CatalogueInfo catalogueInfo) {
        if (from == IntentValue.JumpToBookCatalogType.NORMAL || from == IntentValue.JumpToBookCatalogType.FROM_ADD_BOOK || from == IntentValue.JumpToBookCatalogType.FROM_BOOK_DESK
                || from == IntentValue.JumpToBookCatalogType.FROM_SCAN || from == IntentValue.JumpToBookCatalogType.FROM_SEARCH_BOOK
                || from == IntentValue.JumpToBookCatalogType.FROM_DESK_BOOK || from == IntentValue.JumpToBookCatalogType.FROM_NEW_DESK_BOOK) {
            if (catalogueInfo.getIsPwd() == 1) {
                //需要密码
                deblockingDialog(catalogueInfo);
            } else {
                //不需要密码
                setLocalData();
                //新结构此处不需要下载
                EpaperJumpManager.jumpToTeaWorkContent(R.string.go_back, TeaCatalogActivity.this, tag, catalogueInfo, mServiceId, mInfo, mEpaperServerList, workTag, publishWorkContentList, JUMP_TO_CHOOSE_WORK_CONTENT);
            }
        }

    }

    private EditText deblockint_edit;
    private RelativeLayout deblocking_cancel;
    private RelativeLayout deblocking_confirm_lay;
    private String pwd;
    private CWDialog cwDialog;

    public void deblockingDialog(final CatalogueInfo catalogueInfo) {
        cwDialog = new CWDialog(TeaCatalogActivity.this);
        cwDialog.setCustomDialog(R.layout.activity_deblocking_dialog);
        deblockint_edit = cwDialog.findViewById(R.id.deblockint_edit);
        deblocking_cancel = cwDialog.findViewById(R.id.deblocking_cancel);
        deblocking_confirm_lay = cwDialog.findViewById(R.id.deblocking_confirm_lay);

        deblocking_cancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                cwDialog.dismiss();
            }
        });
        deblocking_confirm_lay.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (deblockint_edit.getText().toString().equals("")) {
                    ToastUtil.INSTANCE.toastCenterError("请输入密码：");
                    return;
                }
                pwd = deblockint_edit.getText().toString().trim();
                String tag = "22eb4d3820015070";
                String[] str = {pwd, tag};
                StringBuffer pwdstr = new StringBuffer();
                for (int i = 0; i < str.length; i++) {
                    if (i < str.length - 1) {
                        pwdstr.append(str[i] + "_");
                    } else if (i == str.length - 1) {
                        pwdstr.append(str[i]);
                    }
                }
                pwd = CWUtils.md5(CWUtils.md5(String.valueOf(pwdstr)));
                checkServicePwd(catalogueInfo);
            }
        });
        cwDialog.show();
    }

    /**
     * 验证书籍章节密码是否正确
     *
     * @param catalogueInfo
     */
    public void checkServicePwd(final CatalogueInfo catalogueInfo) {
        EpaperDao.getInstance().checkServiceCataloguesPwd(pwd, catalogueInfo.getId(), mInfo.getPackageId(), mServiceId, new BaseCallBack() {
            @Override
            public void failed(int errorCode, Object data) {
                if (errorCode == 1) {
                    ToastUtil.INSTANCE.toastCenterError("密码错误");
                } else {
                    ToastUtil.INSTANCE.toastCenterError("验证密码发生 错误");
                }
            }

            @Override
            public void failed(Object data) {

            }

            @Override
            public void success(Object data) {
                cwDialog.dismiss();
                super.success(data);
                //不需要密码
                setLocalData();
                //新结构此处不需要下载
                EpaperJumpManager.jumpToTeaWorkContent(R.string.go_back, TeaCatalogActivity.this, tag, catalogueInfo, mServiceId, mInfo, mEpaperServerList, workTag, publishWorkContentList, JUMP_TO_CHOOSE_WORK_CONTENT);

            }
        });
    }

    /**
     * 获取保存本地作业内容
     */
    public void getLocalPublishWork() {
        ThreadTask.getInstance().executorDBThread(new Runnable() {
            @Override
            public void run() {
                SerializableManager.getInstance().deSerialize(SerializableManager.SerializeKey.SHARE_KEY_CHOOSE_WORK_CONTENT, new BaseCallBack() {
                    @Override
                    public void failed(int errorCode, Object data) {
                        //updateUI();
                    }

                    @Override
                    public void failed(Object data) {
                        // updateUI();

                    }

                    @Override
                    public void success(Object data) {
                        try {
                            if (data != null) {
                                //获取本地DownLoadInfos
                                publishWorkContentList = (ArrayList<PublishWorkContent>) data;
                                if (null != publishWorkContentList && publishWorkContentList.size() > 0) {
                                    work_content_lay.setVisibility(View.VISIBLE);
                                    int workCount = publishWorkContentList.size();
                                    work_content_count_text.setText(workCount + "");
                                } else {
                                    work_content_lay.setVisibility(View.GONE);
                                }

                                setWorkLong();
                            }
                            //updateUI();
                        } catch (Exception e) {
                            e.getStackTrace();
                        }

                    }
                });
            }
        }, ThreadTask.ThreadPeriod.PERIOD_HIGHT);

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == JUMP_TO_CHOOSE_WORK_CONTENT) {
            publishWorkContentList = (List<PublishWorkContent>) data.getSerializableExtra(IntentFlag.INTENT_FLAG_OBJ_LIST);
            if (null != publishWorkContentList && publishWorkContentList.size() > 0) {
                work_content_lay.setVisibility(View.VISIBLE);
                int workCount = publishWorkContentList.size();
                work_content_count_text.setText(workCount + "");
            } else {
                work_content_lay.setVisibility(View.GONE);
            }
            setWorkLong();
        }
    }

    /**
     * 缓存选择内容到本地
     */
    public void setLocalData() {
        SerializableManager.getInstance().serialize(SerializableManager.SerializeKey.SHARE_KEY_CHOOSE_WORK_CONTENT, (Serializable) publishWorkContentList);
    }


    /**
     * 设置作业时长
     */
    public void setWorkLong() {
        refAnswerTime = 0;
        if (null != publishWorkContentList) {
            for (int i = 0; i < publishWorkContentList.size(); i++) {
                refAnswerTime = refAnswerTime + publishWorkContentList.get(i).getRefLong();
            }
        }
        int workRefLong = ((int) (Math.ceil((double) refAnswerTime / 60)));
        if (workRefLong > 0) {
            SpannableStringBuilder chooseWorkLongText = new SpannableStringBuilder("预计 " + workRefLong + " 分钟");
            ForegroundColorSpan GreenSpan = new ForegroundColorSpan(Color.parseColor("#5ce191"));
            if (workRefLong >= 100) {
                chooseWorkLongText.setSpan(GreenSpan, 3, 6, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
            } else if (workRefLong < 100 && workRefLong >= 10) {
                chooseWorkLongText.setSpan(GreenSpan, 3, 5, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
            } else {
                chooseWorkLongText.setSpan(GreenSpan, 3, 4, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
            }
            refAnswerTime_text.setVisibility(View.VISIBLE);
            refAnswerTime_text.setText(chooseWorkLongText);
        } else {
            refAnswerTime_text.setVisibility(View.GONE);
        }
    }


    private class ViewPageTest extends StaticPagerAdapter {

        private List<String> titleChar;

        public ViewPageTest(List<String> tTitleChar) {
            if (tTitleChar == null) {
                tTitleChar = new ArrayList<String>();
            }
            this.titleChar = tTitleChar;
        }

        @Override
        public CharSequence getPageTitle(int position) {
            return this.titleChar.get(position);
        }

        @Override
        public int getCount() {
            return this.titleChar.size();
        }

        @Override
        public View getView(ViewGroup container, int position) {
            View mianView = mInflater.inflate(R.layout.catalog_page, null);
            final LayersView layersView = (LayersView) mianView.findViewById(R.id.layear_layout);
            View sortView = mianView.findViewById(R.id.scor_item);
            ((TextView) mianView.findViewById(R.id.tv_updated)).setText("已更新" + catelogBean.getPublished() + "个章节");
            ((TextView) mianView.findViewById(R.id.count_id)).setText("/共" + catelogBean.getPeriods() + "个章节");
            layersView.setForm(from);
            layersView.setKaoShi(mInfo.getRequired());
            layersView.setBookchapters(bookchapters);
            layersView.setCatalogueInfos(mCatalogueInfos);

            sortView.setVisibility(View.VISIBLE);
            final ImageView sortImage = (ImageView) mianView.findViewById(R.id.sort_iocn);

            if (catelogBean.getIsdesc() == 1) {
                //降序
                sortImage.setImageResource(R.mipmap.sort_rev);
                layersView.setSortState(true);
            } else {
                sortImage.setImageResource(R.mipmap.sort_def);
                layersView.setSortState(false);
            }

            mianView.findViewById(R.id.sco_lin).setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (layersView.sort()) {
                        sortImage.setImageResource(R.mipmap.sort_rev);
                    } else {
                        sortImage.setImageResource(R.mipmap.sort_def);
                    }
                }
            });
            handleCatalogClick(layersView);
            return mianView;
        }

    }

    @Override
    public void finish() {
        if (isFavorites) {
            Intent intent = new Intent();
            intent.putExtra(IntentFlag.INTENT_FLAG_BOOLEAN, true);
            setResult(RESULT_OK, intent);
        }
        setLocalData();
        super.finish();
        if (!isShow) {
            CWSys.setSharedBoolean(EConstants.SHARE_KEY_FAVORITES_IS_SHOW_LSW_TIP, true);
        }

    }


    /**
     * 处理目录的点击事件
     *
     * @param layersView
     */
    private void handleCatalogClick(LayersView layersView) {

        layersView.setOnItemClickListener(new LayersView.ItemClick() {
            @Override
            public void lastItemClick(Node node, View view) {
                //点击章节
                if (node.isSuo() && from != IntentValue.JumpToBookCatalogType.FROM_BUY_SERVICE_BOOKs) {

                } else if (from == IntentValue.JumpToBookCatalogType.FROM_BUY_SERVICE_BOOKs) {
                    ToastUtil.INSTANCE.toastInCenter(TeaCatalogActivity.this, "请到书桌中查看书籍内容~~");
                    return;
                }
                doClickListener(node.getCatalogueInfo());

            }

            @Override
            public boolean freeForLearnContralItemClick(int item, Node node, Node node0) {
                //对非第一个一级条目 父条目判断
                    /*if (node.getpId() == 0 && item != 0) {
                        ToastUtil.INSTANCE.toastInCenter(TeaCatalogActivity.this, " 普通 这个条目不是第一个根节点");
                        return false;
                    }
                    //对第一个条目 父条目判断
                    if (node.getpId() == 0 && item == 0) {
                        ToastUtil.INSTANCE.toastInCenter(TeaCatalogActivity.this, "普通  这个条目被控制 第一个父节点");
                        return true;
                    }
                    //对第一个父条目 下 子二级目录判断
                    if (node.getpId() != 0 && node.getpId() == node0.getId()) {
                        ToastUtil.INSTANCE.toastInCenter(TeaCatalogActivity.this, "普通  这个条目被控制 子节点");
                        return true;
                    }
                    //对第一个父条目 下 子三级目录判断
                    if (node.getpId() != 0 && node.getParent() != null && node.getParent().getpId() == node0.getId()) {
                        ToastUtil.INSTANCE.toastInCenter(TeaCatalogActivity.this, "普通 这个条目被控制 子 子节点");
                        return true;
                    }
                    ToastUtil.INSTANCE.toastInCenter(TeaCatalogActivity.this, "普通 这个是非第一个一级条目 最后");
                    return false;*/
                return true;

            }
        });
    }

    @Override
    public void onClick(View v) {
        int id = v.getId();
        if (id == R.id.favorive_book_img) {
            if (mInfo.getIstop() == 1) {
                setUserBookTop(0, mInfo.getProductId(), mInfo.getServiceId());
            } else {
                setUserBookTop(1, mInfo.getProductId(), mInfo.getServiceId());
            }
        } else if (id == R.id.favorive_book_img2) {
            if (mInfo.getIstop() == 1) {
                setUserBookTop(0, mInfo.getProductId(), mInfo.getServiceId());
            } else {
                setUserBookTop(1, mInfo.getProductId(), mInfo.getServiceId());
            }
        }
    }

    public void setUserBookTop(final int istop, int productid, int serviceid) {
        EpaperDao.getInstance().setUserBookTop(istop, productid, serviceid, new BaseCallBack() {
            @Override
            public void failed(int errorCode, Object data) {
                if (data instanceof TimeoutError) {
                    hideCricleProgress();
                    if (mInfo.getIstop() == 1) {
                        ToastUtil.INSTANCE.toastCenterError("取消收藏失败，检查网络重新请求");
                    } else {
                        ToastUtil.INSTANCE.toastCenterError("收藏失败，检查网络重新请求");
                    }

                } else {

                    hideCricleProgress();
                    if (mInfo.getIstop() == 1) {
                        ToastUtil.INSTANCE.toastCenterError(getString(R.string.cancel_favorite_faild_try_later));
                    } else {
                        ToastUtil.INSTANCE.toastCenterError(getString(R.string.favorite_faild_try_later));
                    }
                }
            }

            @Override
            public void failed(Object data) {
                hideCricleProgress();
                if (mInfo.getIstop() == 1) {
                    ToastUtil.INSTANCE.toastCenterError(getString(R.string.cancel_favorite_faild_try_later));
                } else {
                    ToastUtil.INSTANCE.toastCenterError(getString(R.string.favorite_faild_try_later));
                }
            }

            @Override
            public void success() {
                super.success();
                postMessage();
                isFavorites = true;
                if (mInfo.getIstop() == 1) {
                    ToastUtil.INSTANCE.toastCenterSuccess("取消收藏成功");
                    mInfo.setIstop(0);
                    favorites_lay.setVisibility(View.GONE);
                    favorites_lay2.setVisibility(View.VISIBLE);
                    if (isShow) {
                        favorites_tip2.setVisibility(View.GONE);
                    } else {
                        favorites_tip2.setVisibility(View.VISIBLE);
                    }
                } else {
                    ToastUtil.INSTANCE.toastCenterSuccess("收藏成功");
                    mInfo.setIstop(1);
                    favorites_lay.setVisibility(View.VISIBLE);
                    favorites_lay2.setVisibility(View.GONE);
                    if (isShow) {
                        favorites_tip1.setVisibility(View.GONE);
                    } else {
                        favorites_tip1.setVisibility(View.VISIBLE);
                    }
                }
            }
        });
    }

    public void postMessage() {
        //有收藏or取消收藏 通知首页刷新数据
        EventBus.getDefault().post(new RefreshNewBookDesk(true));
    }

    @Override
    protected void onResume() {
        super.onResume();
    }

    @Override
    protected void onStop() {
        super.onStop();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }

    /**
     * 用于监听pageview
     *
     * @param position
     */
    public void onPageSelected(int position) {
        //显示的
        //        if (mViewPageTitleXiFu.getVisibility() == View.VISIBLE) {
        //            mScrollView.scrollTo(0, (int) (page_titles.getY() - page_titles.getHeight()));
        //        }
    }

}
